package com.wzy.services.http.services;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 互联网IP地址获取
 *
 * @author 陈杰
 * @since 2017/7/15 15:36
 * Copyright ChenJie(wuzhiyun@aliyun.com)
 */
public class InternetIp {

    /**
     * 从http://1212.ip138.com/ic.asp网站获取互联网ip地址
     *
     * */
    public static String getInternetIpFromIpip138(){
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://2017.ip138.com/ic.asp");
        httpGet.setHeader("Accept-Charset", "UTF-8");
        httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpGet.setHeader("Content-Type", "text/html;charset=gb2312");
        httpGet.setConfig(RequestConfig.custom().setConnectTimeout(3000)
                .setSocketTimeout(3000).setConnectionRequestTimeout(3000).build());
        try {
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseBody = EntityUtils.toString(entity, "gb2312");
                int subIndexStart = responseBody.indexOf("[");
                int subIndexEnd = responseBody.indexOf("]");
                return responseBody.substring(subIndexStart+1,subIndexEnd);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
